package com.it.mytest;

import com.alibaba.fastjson.JSONObject;
import org.eclipse.californium.core.CoapResource;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ResourcesLoader {
    //private final static String Path = new File(".").get() + File.separator + "resources";
    // private final static String Path = "E:\\workspace\\iotcenter\\src\\iot-center\\energy-iotcenter-coap\\src\\main\\resources\\";
    private final static String Path;
    static {
        URL resource = ResourcesLoader.class.getClassLoader().getResource("");
        Path = resource.getPath();
       /* String classpath = resource.getPath();
        Path = classpath + File.separator + "coap.json";*/
    }

    private List<ProxyRes> resourcesList;

    public static void main(String[] args) {
        try {
            ResourcesLoader loader = new ResourcesLoader();
            //loader.getResourcesList()
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }

    public ResourcesLoader() throws Exception {
        resourcesList = new ArrayList<ProxyRes>();

        File resources = new File(Path);
        for (String resName : resources.list()) {
            if ("coap.json".equals(resName)) {

                File resFile = new File(resources, resName);
                Reader reader = new FileReader(resFile);
                BufferedReader br = new BufferedReader(reader);
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

                JSONObject o = JSONObject.parseObject(sb.toString());

                //resourcesArr.add(o);
                resourcesList.add(buildObject(o));
            }
        }
    }

    private ProxyRes buildObject(JSONObject o) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        ProxyRes r = new ProxyRes();
        r.setPath(o.getString("endpoint"));
        Class<?> clazz = Class.forName(o.getString("class"));
        CoapResource coapRes = (CoapResource) clazz.newInstance();
        r.setCoapRes(coapRes);

        return r;
    }

    public List<ProxyRes> getResourcesList() {
        return resourcesList;
    }
}
